<template>
  <div id="#app">
    <common-header></common-header>
    <div class="container mt-2">
      <div class="card border-success border-warning">
        <div class="card-header">收货信息</div>
        <div class="list-group list-group-flush" v-if="hasReceiptInfo">
          <p class="list-group-item" v-if="receiptInfo">收货人：{{getUserInfo.realName}}</p>
          <p
            class="list-group-item"
            v-if="receiptInfo"
          >收货地址：{{calcFullAddress+getUserInfo.streetName}}</p>
          <p
            class="list-group-item"
            style="background:none"
            v-if="receiptInfo"
          >手机号码：{{getUserInfo.tel}}</p>
          <div class="tip">
            <a
              @click="editReceiptInfo(
              getUserInfo.id,  
              getUserInfo.realName,
              getUserInfo.tel,
              getUserInfo.streetName,
              getUserInfo.province,
              getUserInfo.city,
              getUserInfo.county
              )"
            >修改</a>
            <a @click="deleterReceiptInfo(getUserInfo.id)">删除</a>
          </div>
        </div>
        <div class="list-group list-group-flush" v-else>
          <p class="list-group-item h5" style="background:none">快来添加一个收货地址哈！</p>
          <div class="tip">
            <a @click="addReceiptInfo(getUserInfo.id)">增加</a>
          </div>
        </div>
      </div>
      <div class="card mt-2 border-success">
        <div class="card-header">请选择支付方式</div>
        <div class="list-group list-group-flush">
          <div class="list-group-item">
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                id="inlineRadio1"
                value="accountMoney"
                name="payMethod"
                checked
                v-model="payMethod"
              >
              <label class="form-check-label" for="inlineRadio1">账户余额</label>
            </div>
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                id="inlineRadio2"
                value="alipay"
                name="payMethod"
                v-model="payMethod"
                disabled
              >
              <label class="form-check-label" for="inlineRadio2">支付宝（未开通）</label>
            </div>
            <div class="form-check form-check-inline">
              <input
                class="form-check-input"
                type="radio"
                id="inlineRadio3"
                value="wechat"
                name="payMethod"
                v-model="payMethod"
                disabled
              >
              <label class="form-check-label" for="inlineRadio3">微信（未开通）</label>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="container mt-4">
      <table class="table table-hover table-responsive-sm table-bordered">
        <thead>
          <tr>
            <th scope="col">商品名</th>
            <th scope="col">数量</th>
            <th scope="col">单价</th>
            <th scope="col">小计</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in calcShopCardNum" :key="index">
            <td>
              <img height="100" :src="item.Pic">
              {{item.D_title}}
            </td>
            <td>{{item.addShopCardNum}}</td>
            <td>{{item.Price | formatMoney}}</td>
            <td>{{item.Price*item.addShopCardNum | formatMoney}}</td>
          </tr>
          <tr>
            <td colspan="4" align="right">
              应付总额：
              <span class="h2 text-danger">{{calcShopCardGoodSum | formatMoney}}</span>
            </td>
          </tr>
          <tr>
            <td colspan="4" align="right">
              <div class="btn-group-sm">
                <button type="button" class="btn btn-primary" @click="postOrder(calcShopCardNum,getUserInfo)">提交订单</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <common-footer></common-footer>
    <div
      class="modal fade"
      id="exampleModal"
      tabindex="-1"
      role="dialog"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">用户信息</h5>
            <button type="button" class="close" @click="cancelModel">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form v-if="newReceiptInfoData.province">
              <div class="form-group">
                <label for="recipient-name" class="col-form-label">收货人:</label>
                <input type="text" class="form-control" id="recipient-name" v-model="newReceiptInfoData.realName">
              </div>

              <div class="form-group">
                <label for="message-text" class="col-form-label">所在地区:</label>
                <div class="form-inline">
                  <select name="province" class="custom-select" v-model="newReceiptInfoData.province">
                    <option :value="province.pid" v-for="(province,index) in receiptInfo['province']" :key="index">{{province.province}}</option>
                  </select>

                  <select name="city" class="custom-select" v-model="newReceiptInfoData.city">
                    <option value="0">--请选择--</option>
                    <option :value="city['id']" v-for="(city,index) in receiptInfo['city']['10123']" :key="index">{{city['city']}}</option>
                  </select>

                  <select name="county" class="custom-select" v-model="newReceiptInfoData.county">
                    <option value="0">--请选择--</option>
                    <option :value="county.id" v-for="(county,index) in receiptInfo['county'][newReceiptInfoData.city]" :key="index">
                      {{county.city}}
                    </option>
                  </select>
                </div>
              </div>

              <div class="form-group">
                <label class="col-form-label">详情地址:</label>
                <textarea class="form-control" placeholder="如道路,门牌号,小区号楼栋号,单元室等" v-model="newReceiptInfoData.streetName"></textarea>
              </div>

              <div class="form-group">
                <label for="mobileNum" class="col-form-label">手机号码:</label>
                <input type="text" class="form-control" id="mobileNum" v-model="newReceiptInfoData.tel">
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="cancelModel">取消</button>
            <button type="button" class="btn btn-primary" @click="modifyReceiptInfo">确定</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import commonHeader from "./common/header.vue";
import commonFooter from "./common/footer.vue";
import $ from "jquery"
import moment from "moment"
export default {
  components: {
    commonHeader,
    commonFooter
  },
  data() {
    return {
      receiptInfo: {},
      newReceiptInfoData: {
        id:"",
        realName:"",
        tel:"",
        streetName:"",
        province:"",
        city:"",
        county:""
      },
      i:0,
      payMethod:'accountMoney'
    };
  },
  watch:{
    "newReceiptInfoData.city":function(){
        this.i++;
        if(this.i>1){
          this.newReceiptInfoData.county=0;
          this.i=0;
        }
    }
  },
  filters: {
    formatMoney(value) {
      return "¥ " + value.toFixed(2);
    }
  },
  computed: {
    calcShopCardNum() {
      return this.$store.getters.getShopCartGood;
    },
    calcShopCardGoodSum() {
      let goods = this.$store.getters.getShopCartGood;
      let sum = 0;
      for (let item of goods) {
        sum = sum + item.Price.toFixed(2) * item.addShopCardNum.toFixed(2);
      }
      return sum;
    },
    getUserInfo() {
      let userList = this.$store.getters.getUser;
      let whicthUser = [];
      for (let item of userList) {
        if (item["isLogin"] == true) {
          whicthUser = item;
          break;
        }
      }
      return whicthUser;
    },
    hasReceiptInfo() {
      let userList = this.$store.getters.getUser;
      let flag = false;
      for (let item of userList) {
        if (item["isLogin"] == true) {
          if (typeof item["realName"] != undefined && item["realName"] != "" && item["realName"].legnth != 0) {
            flag = true;
            break;
          }
        }
      }
      return flag;
    },
    calcFullAddress(){
        if(this.receiptInfo.province!=undefined){
          let userProvince = this.getUserInfo.province;
          let userCity = this.getUserInfo.city;
          let userCounty = this.getUserInfo.county;          
          let province = this.receiptInfo["province"];
          let city = this.receiptInfo["city"][userProvince];
          let county = this.receiptInfo["county"][userCity];
          let fullAddress = {};
          for (let itemProvince of province) {
            if (itemProvince["pid"] == userProvince) {
              fullAddress["province"] = itemProvince["province"];
              break;
            }
          }
          for (let itemCity of city) {
            if (itemCity["id"] == userCity) {
              fullAddress["city"] = itemCity["city"];
              break;
            }
          }
          for (let itemCounty of county) {
            if (itemCounty["id"] == userCounty) {
              fullAddress["county"] = itemCounty["city"];
              break;
            }
          }
          return fullAddress.province+fullAddress.city+fullAddress.county;            
        }else{
          return false;
        }
    } 
  },
  created() {
    this.getReceiptInfo();
  },
  methods: {
    getReceiptInfo() {
      this.axios.get("./fujian.json").then(result => {
        this.receiptInfo = result.data;
      });

      if(localStorage.getItem('newReceiver') != null){
        let LocalReceiverData =JSON.parse(localStorage.getItem('newReceiver'));
        for(let item of LocalReceiverData){
          if(item.id==this.getUserInfo.id){
            this.$store.commit('modifyUserReceiptAddress',item);
            break;
          }
        }
      }

      
    },
    editReceiptInfo(id,realName, tel, streetName,province,city,county) {
      this.newReceiptInfoData["id"]=id;
      this.newReceiptInfoData["realName"]=realName;
      this.newReceiptInfoData["tel"]=tel;
      this.newReceiptInfoData["streetName"]=streetName;
      this.newReceiptInfoData["province"]=province;
      this.newReceiptInfoData["city"]=city;
      this.newReceiptInfoData["county"]=county;
      $('.modal').modal('toggle');
    },
    addReceiptInfo(id){
      this.newReceiptInfoData["id"]=id;
      this.newReceiptInfoData["province"]='10123';
      this.newReceiptInfoData["city"]=0;
      this.newReceiptInfoData["county"]=0;
      $('.modal').modal('toggle');
    },
    cancelModel(){
      this.newReceiptInfoData={
        id:'',
        realName:"",
        tel:"",
        streetName:"",
        province:"",
        city:"",
        county:""
      };
      $('.modal').modal('toggle');
    },
    deleterReceiptInfo(userId){
      if(localStorage.getItem('newReceiver') != null){
        let LocalReceiverData =JSON.parse(localStorage.getItem('newReceiver'));
        for(let i=0;i<LocalReceiverData.length;i++){
          if(LocalReceiverData[i].id==userId){
              LocalReceiverData.splice(i,1);
              break;
          }
        }
        localStorage.setItem('newReceiver',JSON.stringify(LocalReceiverData));  
      }

      this.newReceiptInfoData={
        id:'',
        realName:"",
        tel:"",
        streetName:"",
        province:"",
        city:"",
        county:""
      };      
      this.$store.commit('deleterUserReceiptAddress',userId);

    },
    modifyReceiptInfo(){
      if(localStorage.getItem('newReceiver') != null){
          let LocalReceiverData =JSON.parse(localStorage.getItem('newReceiver'));
          let find=false;
          for(let i=0;i<LocalReceiverData.length;i++){
            if(LocalReceiverData[i].id==this.newReceiptInfoData.id){
                LocalReceiverData.splice(i,1,this.newReceiptInfoData);
                find=true;
                break;
            }
          }
          if(find){
            localStorage.setItem('newReceiver',JSON.stringify(LocalReceiverData));  
          }else{
            LocalReceiverData.push(this.newReceiptInfoData);
            localStorage.setItem('newReceiver',JSON.stringify(LocalReceiverData));            
          }
                     
      }else{
        let newReceiver=[];
        newReceiver.push(this.newReceiptInfoData);
        localStorage.setItem('newReceiver',JSON.stringify(newReceiver));
      }


      this.$store.commit('modifyUserReceiptAddress',this.newReceiptInfoData);
      $('.modal').modal('toggle');
    },
    postOrder(shopCardInfo,userInfo){
     if(Number.parseFloat(userInfo['accountMoney']) < Number.parseFloat(this.calcShopCardGoodSum)){
       let tempUserOrder={
            purchaseGoods:[
             ...shopCardInfo
            ],
            orderId:moment().format('YYYYMMDDHHmmss')+String(userInfo.id)+String(Number.parseInt(Math.random()*100)),
            payStatus:false,
            payTime:new Date().getTime(),
            payMethod:this.payMethod,
            userId:userInfo.id,
            goodsSum:Number.parseFloat(this.calcShopCardGoodSum)
      };
      this.$store.commit("addUserOrder",tempUserOrder);      
      this.$router.push({path:`/payresult/0/${tempUserOrder.orderId}`});
     }else{
       let tempUserOrder={
            purchaseGoods:[
             ...shopCardInfo
            ],
            orderId:moment().format('YYYYMMDDHHmmss')+String(userInfo.id)+String(Number.parseInt(Math.random()*100)),
            payStatus:true,
            payTime:new Date().getTime(),
            payMethod:this.payMethod,
            userId:userInfo.id,
            goodsSum:Number.parseFloat(this.calcShopCardGoodSum)
      };
      this.$store.commit("addUserOrder",tempUserOrder)
      this.$router.push({path:`/payresult/1/${tempUserOrder.orderId}`});
     }
   }
  }
};
</script>

<style scoped>
.tip {
  display: none;
  position: absolute;
  top: calc(53%);
  width: calc(32%);
  height: 30px;
  left: calc(35%);
  text-align: center;
  background: #fff;
}
.tip a {
  color: blue !important;
  font-weight: 600;
  padding: 2px;
  font-size: 20px;
  border: 1px solid red;
  border-radius: 35%;
  cursor: pointer;
}
.list-group:hover .tip {
  display: block;
}
</style>
